package com.ruoyi.auth.service.wechat;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

public class WechatHelper {

    private static String WECHAT_ACCESS_TOKEN = "wechat_access_token";
    private static String SESSION_KEY = "session_key";
    private static String GETTOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=P_APPID&secret=P_SECRET";
    private static String GETOPENIDURL = "https://api.weixin.qq.com/sns/jscode2session?appid=P_APPID&secret=P_SECRET&js_code=P_CODE&grant_type=authorization_code";

    public String getAccountToken(RestTemplate restTemplate, RedisService redisService, String appId, String appSecret) {
        String accessToken = redisService.getCacheObject(appId + WECHAT_ACCESS_TOKEN);
        System.out.println("accessToken:" + accessToken);
        if(accessToken == null || accessToken.length() == 0){
            String tokenResult = restTemplate.getForObject(GETTOKENURL.replace("P_APPID", appId).replace("P_SECRET", appSecret), String.class);

            JSONObject tokenJsonObject = JSONObject.parseObject(tokenResult);
            System.out.println(tokenJsonObject);
            accessToken = tokenJsonObject.getString("access_token");
            redisService.setCacheObject(appId + WECHAT_ACCESS_TOKEN, accessToken, 119L, TimeUnit.MINUTES); //2个小时失效 设置 1个半小时 不能改
        }
        return accessToken;
    }

    public String getOpenId(RestTemplate restTemplate, String appId, String appSecret, String code) {
        String openid = "";
        if(code != null && code.length() > 0){
            String tokenResult = restTemplate.getForObject(GETOPENIDURL.replace("P_APPID", appId).replace("P_SECRET", appSecret).replace("P_CODE", code), String.class);

            JSONObject tokenJsonObject = JSONObject.parseObject(tokenResult);
            System.out.println("获取openid：" + tokenResult);
            openid = tokenJsonObject.getString("openid");
            String session_key = tokenJsonObject.getString("session_key");
        }

        return openid;
    }
}
